package com.marketapp.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;

import com.marketapp.domain.Sector;
import com.marketapp.domain.UserInfo;
import com.marketapp.helper.DaoException;
import com.marketapp.util.StringUtil;

public class UserDaoImpl implements IUserDao {

	@Autowired
	SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public void createUser(UserInfo userInfo) throws DaoException {
		Session session = sessionFactory.openSession();
		Transaction transaction = session.getTransaction();
		try {
			transaction.begin();
			session.save(userInfo);
			transaction.commit();
		} catch (Exception ex) {
			throw new DaoException("Error: User cannot be saved "
					+ userInfo.getUserName(), ex.getCause());
		} finally {
			session.close();
		}
	}

	@Override
	public void deleteUser(UserInfo userInfo) {
		// TODO Auto-generated method stub

	}

	@Override
	public UserInfo getUserByName(String userName) throws DaoException {
		Session session = sessionFactory.openSession();
		List<UserInfo> userInfoList = new ArrayList<UserInfo>();
		try {
			Query query = session.getNamedQuery("getUserByName").setString(
					"userName", StringUtil.getStringUpperCase(userName));
			userInfoList = query.list();
			if(userInfoList.size()>0){
				return userInfoList.get(0);
			}else{
				return null;
			}
		} catch (Exception ex) {
			throw new DaoException("Error: User cannot be retreived ",
					ex.getCause());
		} finally {
			session.close();
		}
	}

	@Override
	public List<String> getUserAuthorities(String userName) {
		// TODO Auto-generated method stub
		return null;
	}

}
